<template>
  <div>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="70%">
      <div class="diabianjireport">
        <div class="titlebox">
          <div></div>
          <div class="text">{{ reportvalue.companyName }} {{ reportvalue.dateString }} 能耗分析报告</div>
          <div class="butt">
            <el-button type="primary" size="small" @click="makepdf">生成pdf报告</el-button>
            <el-button type="primary" size="small" :disabled="entityvalue.createPdfFlag?false:true" @click="xiazaipdf">下载报告</el-button>
          </div>
        </div>
        <div class="xiangqing">
          <span>用电企业: {{ reportvalue.companyName }}</span>
          <span>报告类型：{{ radio3=='2'?'月':'年' }}报</span>
          <span>时间周期：{{ reportvalue.dateString }}</span>
        </div>
        <el-divider></el-divider>
        <div class="zhutibb">
          <div>尊敬的{{ reportvalue.companyName }}:</div>
          <div class="zuoshuo">
            <div class="werare">我们对贵公司总体用能情况，重点用能设备能耗情况进行了全方位监测,{{ reportvalue.dateString }}企业总用电量{{ entityvalue.totalElectricUsage }}kWh,
                 总电费{{ entityvalue.totalElectricAmount }}元，并以监测数据为依据，对企业的能耗水平通过同环比分析及产品单位能耗，单位产值能耗进行了评估，现就企业
                 {{ reportvalue.dateString }}的总体情况进行总结，生成能耗分析报告，提出符合贵单位的节能建议，详情如下：
            </div>
            <div>1. 总体用电</div>
            <div class="toltit">通过对企业用电量的监测，{{ reportvalue.dateString }}贵公司尖峰平谷各时段用电量，总用电量情况如下：</div>
            <div class="jian"><span class="fourshi">尖时段电量:{{ entityvalue.sharpUsage }} kWh</span> <span class="fourshi">尖时段电费:{{ entityvalue.sharpAmount }} 元</span></div>
            <div class="jian"><span class="fourshi">峰时段电量:{{ entityvalue.peakUsage }} kWh</span> <span class="fourshi">峰时段电费:{{ entityvalue.peakAmount }} 元</span></div>
            <div class="jian"><span class="fourshi">平时段电量:{{ entityvalue.flatUsage }} kWh</span> <span class="fourshi">平时段电费:{{ entityvalue.flatAmount }} 元</span></div>
            <div class="jian"><span class="fourshi">谷时段电量:{{ entityvalue.valleyUsage }} kWh</span> <span class="fourshi">谷时段电费:{{ entityvalue.valleyAmount }} 元</span></div>
            <div class="jian"><span class="fourshi">总电量:{{ entityvalue.totalElectricUsage }} kWh</span> <span class="fourshi">总电费:{{ entityvalue.totalElectricAmount }} 元</span><span>平均电价:{{ entityvalue.avgElectricAmount }} 元/kWh</span></div>
            <div class="biaoone">工厂总用电主要用电和辅助用电，{{ reportvalue.dateString }}企业的分项用能情况日下：</div>
            <div class="tableone">
              <!-- <TableColumn
              :tableData="entityvalue.mainAuxiliaryEquipData" 
              :tableConfig="tableConfig" 
              :issize="'mini'"></TableColumn> -->
              <el-table
                :data="entityvalue.mainAuxiliaryEquipData"
                issize="mini"
                 border
                 v-loading="eleloading"
                :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                style="width: 100%">
                <el-table-column
                  prop="name"
                  width="100"
                  label="主/辅设备">
                </el-table-column>
                <el-table-column
                  prop="sharpUsage"
                  label="尖时段电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="peakUsage"
                  label="峰时段电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="flatUsage"
                  label="平时段电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="valleyUsage"
                  label="谷时段电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="totalElectricUsage"
                  label="总电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="totalElectricAmount"
                  label="总电费(元)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="avgElectricAmount"
                  label="平均电价(元/kWh)"
                  align="right">
                </el-table-column>
              </el-table>
            </div>
            <div class="nenghaofenbu">2. 能耗分布</div>
            <div class="treeechart" ref="treeechart"></div>
            <div class="dianfenbu">
              通过用电分布分析，{{ reportvalue.dateString }}
              <span v-for="(item,index) in array" :key="index">{{ item.name }} ({{ item.value }}kWh)&nbsp;</span> &nbsp;
              <span class="zhabi">【占比超10%】</span> 等用能单元的电量占比较大，请重点关注这些用能单元的用能情况
            </div>
            <div>3. 同环比分析</div>
            <div class="huanbiechart " ref="huanbiechart"></div>
            <div>通过同环比分析，合计存在 <span  v-if="radio3 == '2'">{{ huanbiobj.daysExceedLastMonth }}天超过上月同期20%,</span>{{ huanbiobj.daysExceedLastYear }}天超过去年同期20%。</div>
            <div class="xiansun">4. 线损分析</div>
            <div class="tabletwo">
              <el-table
                :data="tableData"
                issize="mini"
                v-loading="energyloading"
                 border
                :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                style="width: 100%">
                <el-table-column
                  type="index"
                  width="80"
                  align="center"
                  label="序号">
                </el-table-column>
                <el-table-column
                  prop="dateTime"
                  label="日期"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="attritionModelName"
                  label="损耗模型名称">
                </el-table-column>
                <el-table-column
                  prop="upMeterValue"
                  label="输入电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="lowMeterValue"
                  label="输出电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="attritionValue"
                  label="损耗电量(kWh)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="attritionRate"
                  label="损耗率(%)"
                  align="right">
                </el-table-column>
                <el-table-column
                  prop="attritionLevel"
                  label="损耗级别">
                </el-table-column>
              </el-table>
            </div>
            <div>通过线损分析,共有 {{ xiansunlist.length }} 条线路的线损超过10%，具体如下:
              <span v-for="(item,index) in xiansunlist" :key="index">{{item.attritionModelName}} 线损{{ item.attritionRate }}%</span>
              。请检查是否存在线路规划不合理，导线选型有误以及线路老化问题
            </div>
            <div class="yonenerg">
              <div>5. 用能建议</div>
              <div class="xiang">
                <div>1. 根据用能分布情况，重点关注能耗较大用能单元的节能改造</div>
                <div>2. 结合公司平均电价情况，合理安排生产计划，充分利用分时电价，降低用电成本</div>
                <div>3. 结合同环比，能耗性能评估等分析，即使查找用能异常原因并解决</div>
                <div>4. 如果场内线路线损较高，条件允许情况下重新规划设计厂内输配电系统，降低用用能损耗</div>
                <div>5. 建立能源管理体系，指标未达标的生产线，加强班组员工培训，提升熟练度，另外注重生产线设备技术大修，提高设备能效</div>
              </div>
            </div>
            <div class="shuo">
              <div>5. 说明</div>
              <div class="shuoming">
                 <div>1. 本报告得出的用能评价及提出的用能建议是根据用能监测数据分析所得，具体情况需要相关人员结合生产实际情况进行判断</div>
                 <div>2. 因电能监测终端的安装位置，采集精度，统计周期与电网公司计量设备存在较大差异，本报告不能作为用电企业与售电公司电费结算的依据</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import download from 'downloadjs'
import {getfengxilistapi}from '@/api/energy-consumption/Basic-analysis/Model-Loss'
import { gettongbarechapi } from '@/api/energy-consumption/Basic-analysis/EnergyCosts'
import * as echarts from 'echarts';
import {ColorList,convertChildrenListToChildren,shuffleArray} from '@/utils/array'
import TableColumn from '@/components/Table/index.vue'
import {getelectlistapi} from '@/api/energy-consumption/Basic-information/FlowDirection'
import {getlookreportlistapi,exportpdfapi,getxiazaipdfapi} from '@/api/energy-consumption/factory-energy/UseEnergyReport'
export default {
  name: 'CallPoliceBianjireport',
  props: {
    reportvalue: {
      type: Object,
    },
    treevalue: {
      type: Object,
    },
    radio3: {
      type:String
    }
  },
  components: {
    TableColumn
  },
  data() {
    return {
      dialogVisible:false,
      entityvalue: {},
      array: [],
      huanbiobj:{},
      tableData:[],
      xiansunlist:[],
      treemyChart: null,
      barmyChart:null,
      treeloading: null,
      barloading:null,
      eleloading: false,
      energyloading:false
    };
  },

  mounted() {
    
  },

  methods: {
    // 导出pdf
    async makepdf() {
      const energyDistributionChart = this.treemyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const tbChart=this.barmyChart.getDataURL({
        pixelRatio:2,
        backgroundColor:'#fff'
      })
      const overLimitDevice = this.array.map(ele =>`${ele.name}(${ele.value})`)
      const lineLossDetails = this.xiansunlist.map(ele =>`${ele.attritionModelName}(${ele.attritionRate})`)
      const res=await exportpdfapi({
        energyDistributionChart, tbChart, id: this.reportvalue.id, overLimitDevice:overLimitDevice.join(','),
        lineLossCount: this.xiansunlist.length,lineLossDetails:lineLossDetails.join(',')
      })
      this.$message({
        type: res.code == '200' ? 'success' : 'warning',
        message: res.code == '200' ? '报告生成成功':res.message
      })
    },
    // 点击浏览调取接口
    async getbaogaolist() {
      this.array = []
      this.huanbiobj = {}
      this.treeloading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: this.$refs.treeechart
      });
      this.barloading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: this.$refs.huanbiechart
      });
      // 获取基础数据
      this.eleloading=true
      const {data:{entity}} = await getlookreportlistapi(this.reportvalue.id)
      this.entityvalue = entity
      this.eleloading=false
      //  获取树图图表
      const res = await getelectlistapi({
        calculateDifferenceValueFlag: true, type: '1', companyId: this.treevalue.companyId,
        dateType:this.radio3,dateString:this.reportvalue.dateString
      })
      //  获取树图图表
      this.getelecechart(res.data.entity)
      this.gettreevalueorlist([res.data.entity])
      // 获取同环比图表
      const {data:{list}}=await gettongbarechapi({classId:this.treevalue.companyId,dateString:this.reportvalue.dateString,dateType:this.radio3,energyType:'01'})
      this.getnenghaoech(list)
      if (this.radio3 == '2') {
        this.huanbiobj=this.compareData(list)
      } else {
        this.huanbiobj=this.compareYear(list)
      }
      // 获取线损分析数据
      this.getdatalist()
    },
    // 下载pdf
    async xiazaipdf() {
      axios({
        method: 'POST',
        url:`/biz/ecm-microservice-biz/ecm/factory/energy/download/pdf?id=${this.reportvalue.id}`,
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data], { type: 'application/pdf'})
        download(blob, `能耗分析报告.pdf`)
        })

    },
    // 获取表格数据
    async getdatalist() {
      this.energyloading=true
      const { data: { list, totalCount,entity } } = await getfengxilistapi({
        pageNo: 0, pageSize: 100,energyTypeId:'01',dateType:this.radio3,attritionLevel:'',
        companyId:this.treevalue.companyId,dateString:this.reportvalue.dateString,attritionModelName:''
      })
      this.tableData = list
      this.xiansunlist= list.filter(ele => {
        if (ele.attritionRate>10) {
          return ele
        }
      })
      this.energyloading=false
    },
    // 更具同环比数据遍历出超上期的天数
    compareData(list) {
      let currentData = list.find(item => item.name === '本期').datalist;
        let lastMonthData = list.find(item => item.name === '上月同期').datalist;
        let lastYearData = list.find(item => item.name === '去年同期').datalist;
        let daysExceedLastMonth = 0;
        let daysExceedLastYear = 0;
        for (let i = 0; i < currentData.length; i++) {
          let currentValue = parseFloat(currentData[i].valueReading);
          let lastMonthValue = parseFloat(lastMonthData[i].valueReading);
          let lastYearValue = parseFloat(lastYearData[i].valueReading);
          if (currentValue > lastMonthValue) {
            daysExceedLastMonth++;
          }
          if (currentValue > lastYearValue) {
            daysExceedLastYear++;
          }
        }
        return { daysExceedLastMonth, daysExceedLastYear };
    },
    // 获取同环比同期超去年本期20%的天数
    compareYear(list) {
      let currentData = list.find(item => item.name === '本期').datalist;
      let lastYearData = list.find(item => item.name === '去年同期').datalist;
      let daysExceedLastYear = 0;
      let thresholdLastYear = 0.2 * parseFloat(lastYearData[0].valueReading);
      for (let i = 0; i < currentData.length; i++) {
        let currentValue = parseFloat(currentData[i].valueReading);
        let lastYearValue = parseFloat(lastYearData[i].valueReading);
        if (currentValue > (lastYearValue + thresholdLastYear)) {
          daysExceedLastYear++;
        }
      }
      return { daysExceedLastYear };
    },
    // 便利数图 取出占比超过10的数据
    gettreevalueorlist(list) {
      list.map(ele => {
        if (ele.percentageValue > 10) {
          this.array.push({name:ele.name,value:ele.value})
        }
        if (ele.children) {
          this.gettreevalueorlist(ele.children)
        }
      })
    },
    // 获取树图
    async getelecechart(entity) {
      var chartDom = this.$refs.treeechart
      var myChart = echarts.init(chartDom);
      
      var option;
      let convertedData = convertChildrenListToChildren(entity,ColorList);
      const data=[convertedData]
      option = {

          tooltip : {
              show: true,
              trigger: 'item',
              formatter: "{b}: {c}",
              backgroundColor:'rgba(250, 250, 250, 0.1)'
          },
          series: {
              top: '1%',
              left: '10%',
              bottom: '1%',
              right: '10%',
              type: 'tree',
              data: data,
            initialTreeDepth: 5,
            lineStyle: {
                color: '#188fff' // 设置线条颜色为红色
            },
              emphasis: {
                  focus: 'ancestor',
              },
              label: {
                  position: 'left',
                  verticalAlign: 'middle',
                  align: 'right',
                  fontSize: 12,
              },
              leaves: {
                  label: {
                      position: 'right',
                      verticalAlign: 'middle',
                      align: 'left',
                  },
              },
          },
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.treemyChart=myChart
      this.treeloading.close()
    },
    // 获取能耗同环比图表
    getnenghaoech(list) {
      var chartDom = this.$refs.huanbiechart
      var myChart = echarts.init(chartDom);
      var option;
      const timePoints=list[0]?.datalist.map(ele=>ele.timeReading)
      const series= list.map(ele => {
        return {
            name:ele.name,
            data: ele.datalist.map(ele=>ele.valueReading),
            type: 'bar',
        }
      })
      option = {
        grid: {
        top: '10%',
        bottom: '7%',
        left: '5%',
        right: '0%',
          },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          right:'center',
        },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:'(kWh)'
          },
        ],
        series: series
      };
      myChart.clear();
      option && myChart.setOption(option);
      this.barmyChart = myChart;
      this.barloading.close()
    },
  },
};
</script>

<style scoped>
.diabianjireport{
  /* font-size: 16px; */
  color: #293343;
  .titlebox{
    display: flex;
    justify-content: space-between;
    .butt{
      text-align: right;
    }
    .text{
      text-align: center;
    }
    div{
      width: 33.3%;
    }
  }
  .xiangqing{
    margin-top: 40px;
    span{
      margin-right: 30px;
    }
  }
  .zhutibb{
    div{
      margin-bottom: 7px;
    }
    .zuoshuo{
      padding-left: 30px;
      .werare{
        margin-bottom: 30px;
      }
      .toltit{
         margin-bottom: 20px;
      }
      .jian{
        .fourshi{
          display: inline-block;
          width: 30%;
        }
      }
      .biaoone, .nenghaofenbu, .dianfenbu, .yonenerg{
        margin: 20px 0;
        .zhabi{
          color: red;
        }
        .xiang{
          padding-left: 20px;
        }
      }
      .xiansun{
        margin-top: 20px;
      }
      .shuo{
        .shuoming{
          padding-left: 20px;
        }
      }
      .treeechart{
        height: 300px;
      }
      .tabletwo{
        margin: 10px 0;
      }
      .huanbiechart{
        margin: 20px 0;
        height: 300px;
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align:center;
}
</style>